package org.oslims.server.service.impl;

import java.util.List;

import net.sf.gilead.gwt.GwtConfigurationHelper;
import net.sf.gilead.gwt.PersistentRemoteService;

import org.hibernate.Session;
import org.oslims.client.service.MixtureComponentService;
import org.oslims.domain.Mixture;
import org.oslims.domain.MixtureComponent;
import org.oslims.server.dao.MixtureComponentDao;
import org.oslims.server.dao.hbm.HbmMixtureComponentDao;
import org.oslims.server.dao.util.HibernateUtil;

import com.google.gwt.validation.client.interfaces.IValidator;
import com.google.gwt.validation.server.ServerValidator;

public class MixtureComponentServiceImpl extends PersistentRemoteService implements MixtureComponentService {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4464139023786525836L;

	MixtureComponentDao mixtureComponentDao;

	IValidator<Mixture> mixtureValidator = new ServerValidator<Mixture>();

	public MixtureComponentServiceImpl() {
		mixtureComponentDao = new HbmMixtureComponentDao();

		net.sf.gilead.core.hibernate.HibernateUtil hibernateUtil = new net.sf.gilead.core.hibernate.HibernateUtil(HibernateUtil.getSessionFactory());
		setBeanManager(GwtConfigurationHelper.initGwtStatelessBeanManager(hibernateUtil));
	}

	@Override
	public void removeMixtureComponents(List<MixtureComponent> mixtureComponents) {

		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		try {
			mixtureComponentDao.setSession(session);

			for (MixtureComponent mc : mixtureComponents) {
				mixtureComponentDao.makeTransient(mc);
			}

			session.getTransaction().commit();
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	@Override
	public void saveOrUpdateMixtureComponents(List<MixtureComponent> mixtureComponents) {

		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		try {
			mixtureComponentDao.setSession(session);

			for (MixtureComponent mc : mixtureComponents) {
				mixtureComponentDao.makePersistent(mc);
			}

			session.getTransaction().commit();
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			throw e;
		} finally {
			session.close();
		}
	}
}
